const { ipcMain, Notification } = require('electron')
const { SerialPort } = require('serialport')

var receive_event
var strLock
ipcMain.on('lock_init', (event, val) => {
    // 定义串口信息
    const port = new SerialPort({
        path: val,
        baudRate: 115200
    },res => {
        if (res != null) {
            new Notification({
                title: 'TIMS NOTICE',
                body: '串口打开失败！'
            }).show()
        }
    })

    port.open(res => {
        try {
            if (res) {
                if (res.message != 'Port is opening') {
                    return console.log('Error opening port: ', res.message)
                }
            }
            event.reply('lock_status', true)
        } catch (error) {
            console.log(error)
        }
    })

    port.on('error', err => {
        e.sender.send('lock_error', err)
    })

    const { DelimiterParser } = require('@serialport/parser-delimiter')
    const parser = port.pipe(new DelimiterParser({ delimiter: toBuffer('0c') }))
    parser.on('data', data => {
        var lock = data.toString('hex')
        var hex = lock.substr(4,2)
        var locks = addZero(parseInt(hex,16).toString(2),6).split('').reverse().join('')
        console.log(locks)
        event.reply('lock_info', locks)
    })
    

    // 发送锁控命令
    ipcMain.on('lock_send',(event,val) => {
        send(val)
    })

    function send(val) {
        //将一个十六进制报文转为字符数组
        strs = val.split(" ");
        for(let i = 0;i<strs.length;i++){
            strs[i] = "0x"+strs[i];
        }//每个字符加上0x
        //将数组放到buffer
        let buffer = Buffer.from(strs);
        port.write(buffer)
        port.drain(err => {
            if (err) {
                return
            }
        })
    }

    function toBuffer(str) {
        //将一个十六进制报文转为字符数组
        strs = str.split(" ");
        for(let i = 0; i < strs.length; i++){
            strs[i] = "0x"+strs[i];
        }//每个字符加上0x
        //将数组放到buffer
        return Buffer.from(strs);
    }

    function addZero(num, n) {
        return (Array(n).join(0) + num).slice(-n)
    }

})


const func = {
  // 发送数据

}



module.exports = func;
